package com.demo.base.rabbitmq.sender;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.demo.base.rabbitmq.constant.MqConstant.*;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description 消息生产者
 * @date 2023/3/10 4:56 PM
 */
@Component
@Slf4j
public class MqSender {

    /** 注入RabbitTemplate模板 */
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public MqSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 发送延时消息
     *
     * @param content
     */
    public void sendTimeoutMsg(String content) {
        // 路由模式发布延时消息
        rabbitTemplate.convertAndSend(
                DELAY_EXCHANGE,
                DELAY_ROUTING_KEY,
                content,
                message -> {
                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    // 毫秒为单位，指定此消息的延时时长
                    message.getMessageProperties().setDelay(DELAY_TIME_MS);

                    return message;
                });

        log.info("延时消息发送成功，消息内容：{}", content);
    }

    /**
     * 发送普通消息
     *
     * @param content
     */
    public void sendMsg(String content) {
        rabbitTemplate.convertAndSend(REAL_TIME_EXCHANGE, REAL_TIME_ROUTING_KEY, content);

        log.info("实时消息发送成功，消息内容：{}", content);
    }
}
